/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.hibernate.model.dao;
import admin.hibernate.pojo.Chitietsanpham;
import admin.hibernate.pojo.Sanpham;
import admin.hibernate.util.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Administrator
 */
public class SanPhamDAO 
{
    //<editor-fold defaultstate="collapsed" desc="1. HQL - Lấy danh sách sản phẩm">
    public static List<Sanpham> LayDanhSachSanPhamHQL()
    {
        List<Sanpham> arrSanPham = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try
        {
            int soSanPhamTrenTrangChu = ThamSoDAO.LaySoSanPhamTrenTrangChu();
            String hql = "select sp from Sanpham sp where tinhTrangXoa=1";
            Query query = session.createQuery(hql);
            query.setMaxResults(soSanPhamTrenTrangChu);
            arrSanPham = query.list();
            session.close();
        }
        catch(HibernateException ex)
        {
            System.out.println(ex);
        }
        return arrSanPham;
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="2. HQL - Lấy chi tiết sản phẩm">
    public static Chitietsanpham LayChiTietSanPhamHQL(int maSanPham)
    {
        Chitietsanpham chitietsp = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try
        {
            String hql = "select ctsp from Chitietsanpham ctsp where ctsp.sanpham.maSanPham=:maSanPham";
            Query query = session.createQuery(hql);
            query.setInteger("maSanPham", maSanPham);
            Object ob = query.uniqueResult();
            chitietsp = (Chitietsanpham)ob;
            session.close();
        }
        catch(HibernateException ex)
        {
            System.out.println(ex);
        }
        return chitietsp;
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="3. Lấy sản phẩm by ID">
    public static Sanpham getProductByID(int maSanPham)
    {
        Sanpham sanPham = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try
        {
            sanPham = (Sanpham) session.get(Sanpham.class, maSanPham);
        }
        catch(HibernateException hex)
        {
            System.err.print(hex);
        }finally
        {
            session.close();
        }
        return sanPham;
    }
    
    //</editor-fold>
    
}
